package leetcode;

public class Demo14 {
    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"abds","abcd","a"}));
    }

    public static String longestCommonPrefix(String[] strs) {
        if(strs.length==1){
            return strs[0];
        }
        //找出前两个字符串的最长公共前缀
        int i = 0;
        while(i<strs[0].length() && i<strs[1].length()){
            if(strs[0].charAt(i)==strs[1].charAt(i)){
                i++;
            }else{
                break;
            }
        }
        if(strs.length<=2){
            return strs[0].substring(0,i);
        }
        //遍历数组，将最长公共前缀范围缩小
        for(int j=2;j<strs.length;j++){
            while(true){
                if(strs[j].length()<i || !strs[j].substring(0,i).equals(strs[0].substring(0,i))){
                    i--;
                }else{
                    break;
                }
            }
        }
        return strs[0].substring(0,i);
    }
}
